package com.suman.bbcticker.widget;

import android.app.AlarmManager;
import android.app.PendingIntent;
import android.appwidget.AppWidgetManager;
import android.appwidget.AppWidgetProvider;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.net.Uri;
import android.os.SystemClock;
import android.preference.PreferenceManager;
import android.util.Log;

import com.suman.bbcticker.R;
import com.suman.bbcticker.configure.PreferenceLauncherActivity;
import com.suman.bbcticker.service.RssReaderService;

public class SkyNewsReaderAppWidget extends AppWidgetProvider {
	public static final String URI_SCHEME = "newsreader_widget";
	static final String TAG = "SkyNewsReaderAppWidget";

	@Override
	public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) {
		SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(context);
		

		for (int mAppWidgetId : appWidgetIds) {
			if (!checkIfZombieAppWidgetInstance(sharedPreferences, mAppWidgetId)) {
				
				Intent newIntent = new Intent(context, RssReaderService.class);
				newIntent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, mAppWidgetId);
				context.startService(newIntent);

			} else {

			}

		}

	}

	
	private boolean checkIfZombieAppWidgetInstance(SharedPreferences sharedPreferences, int appWidgetId) {
		if(appWidgetId == AppWidgetManager.INVALID_APPWIDGET_ID){
			return true;
		}else{
			String widgetSavedState = sharedPreferences.getString(PreferenceLauncherActivity.PREF_PREFIX_KEY + appWidgetId, "");
			if ("".equalsIgnoreCase(widgetSavedState)) {
				return true;
			}
		}
			
		
		return false;
	}

	@Override
	public void onDeleted(Context context, int[] appWidgetIds) {

		for (int appWidgetId : appWidgetIds) {
			// stop alarm
			Intent widgetUpdate = new Intent(context, SkyNewsReaderAppWidget.class);
			widgetUpdate.setAction(AppWidgetManager.ACTION_APPWIDGET_UPDATE);
			widgetUpdate.putExtra(AppWidgetManager.EXTRA_APPWIDGET_IDS, new int[] { appWidgetId });
			widgetUpdate.setData(Uri.withAppendedPath(Uri.parse(URI_SCHEME + "://widget/id/"), String
			        .valueOf(appWidgetId)));
			PendingIntent newPending = PendingIntent.getBroadcast(context, 0, widgetUpdate,
			        PendingIntent.FLAG_UPDATE_CURRENT);

			AlarmManager alarms = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
			alarms.cancel(newPending);

			// remove preference
			removeCommonPreferences(context);
			RssReaderService.alarmTriggerTimeMap.remove(appWidgetId);
		}

		super.onDeleted(context, appWidgetIds);

	}
		
	private void removeCommonPreferences(Context context) {
		Log.e(TAG,"Removing preferences...");
		SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(context);
		SharedPreferences.Editor configEditor = sharedPreferences.edit();
		configEditor.remove(PreferenceLauncherActivity.TICKER_ALERTTYPE_SOUND_KEY);
		configEditor.remove(PreferenceLauncherActivity.TICKER_ALERTTYPE_VIBRATE_KEY);
		configEditor.remove(PreferenceLauncherActivity.TICKER_ALERTTYPE_NOTIFICATION_KEY);
		configEditor.remove(PreferenceLauncherActivity.TICKER_ALERTTYPE_SITESELECTED_KEY);
		configEditor.remove(PreferenceLauncherActivity.TICKER_ALERTTYPE_FEEDREFRESHTIME_KEY);
		configEditor.commit();
	}
	

	@Override
	public void onReceive(Context context, Intent intent) {

		final String action = intent.getAction();

		if (AppWidgetManager.ACTION_APPWIDGET_DELETED.equals(action)) {
			final int appWidgetId = intent.getExtras().getInt(AppWidgetManager.EXTRA_APPWIDGET_ID,
			        AppWidgetManager.INVALID_APPWIDGET_ID);
			if (appWidgetId != AppWidgetManager.INVALID_APPWIDGET_ID) {
				this.onDeleted(context, new int[] { appWidgetId });
			}
		} else if (AppWidgetManager.ACTION_APPWIDGET_UPDATE.equals(action)) {

			if (!URI_SCHEME.equals(intent.getScheme()) && intent.getExtras() != null) {

				final int[] appWidgetIds = intent.getExtras().getIntArray(AppWidgetManager.EXTRA_APPWIDGET_IDS);
				for (int mAppWidgetId : appWidgetIds) {
					// Retrieve shared preference object and do stuff for alarm configuration
					Intent widgetUpdate = new Intent(context, SkyNewsReaderAppWidget.class);
					widgetUpdate.putExtra(AppWidgetManager.EXTRA_APPWIDGET_IDS, new int[] { mAppWidgetId });
					widgetUpdate.setAction(AppWidgetManager.ACTION_APPWIDGET_UPDATE);
					widgetUpdate.putExtra("unique", "unique");

					// make this pending intent unique
					widgetUpdate.setData(Uri.withAppendedPath(Uri.parse(SkyNewsReaderAppWidget.URI_SCHEME
					        + "://widget/id/"), String.valueOf(mAppWidgetId)));
					PendingIntent newPending = PendingIntent.getBroadcast(context, 0, widgetUpdate,
					        PendingIntent.FLAG_UPDATE_CURRENT);

					// schedule the new widget for updating
					AlarmManager alarms = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
					int updateRateInMins = Integer
					        .parseInt(getSharedPreferenceForFeedRefreshTime(context, mAppWidgetId));
					alarms.setRepeating(AlarmManager.ELAPSED_REALTIME, SystemClock.elapsedRealtime(),
					        updateRateInMins * 1000 * 60, newPending);

				}

			} else if (URI_SCHEME.equals(intent.getScheme())
			        && "unique".equalsIgnoreCase(intent.getStringExtra("unique"))) {

			}
			super.onReceive(context, intent);
		} else {
			super.onReceive(context, intent);
		}

	}

	@Override
	public void onDisabled(Context context) {

		RssReaderService.alarmTriggerTimeMap.clear();
		super.onDisabled(context);
	}

	private String getSharedPreferenceForFeedRefreshTime(Context context, int appWidgetId) {
		SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(context);
		String feedRefreshTime = sharedPreferences.getString(PreferenceLauncherActivity.PREF_PREFIX_KEY + appWidgetId
		        + R.id.widget_configuration_feedrefresheditbutton, "10");
		return feedRefreshTime;
	}

}
